package com.zhuang.sort;

import java.util.Arrays;

/**
 * description: 希尔排序
 * date: 2022/9/17 21:54
 * author: Zhuang
 * version: 1.0
 */
public class ShellSort {
    public static void main(String[] args) {
        int[] arr = {101, 34, 119, 1};
        shellSort1(arr);
        shellSort2(arr);
    }

    // 交换法
    public static void shellSort1(int[] arr) {
        int temp;
        int count = 0;
        for (int gap = arr.length / 2; gap > 0; gap /= 2) {
            for (int i = gap; i < arr.length; i++) {
                for (int j = i - gap; j >= 0; j -= gap) {
                    if (arr[j] > arr[j + gap]) {
                        temp = arr[j];
                        arr[j] = arr[j + gap];
                        arr[j + gap] = temp;
                    }
                }
            }
            System.out.println("希尔排序" + (++count) + "轮" + Arrays.toString(arr));
        }
    }

    // 移位法
    public static void shellSort2(int[] arr) {
        int count = 0;
        for (int gap = arr.length / 2; gap > 0; gap /= 2) {
            for (int i = gap; i < arr.length; i++) {
                int j = i;
                int temp = arr[j];
                if (arr[j] < arr[j - gap]) {
                    while (j - gap >= 0 && temp < arr[j - gap]) {
                        // 移动
                        arr[j] = arr[j - gap];
                        j -= gap;
                    }
                    arr[j] = temp;
                }
            }
            System.out.println("希尔排序" + (++count) + "轮" + Arrays.toString(arr));
        }
    }
}
